<template>
  <div class="tag-management">
    <div class="page-header">
      <h1>标签管理</h1>
      <button @click="showAddTagModal = true" class="btn-primary">
        <i class="icon-add"></i>
        添加标签
      </button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="search-box">
        <input 
          type="text" 
          placeholder="搜索标签名称..." 
          v-model="searchQuery"
          @input="handleSearch"
        />
        <i class="icon-search"></i>
      </div>
    </div>

    <!-- 标签列表表格 -->
    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>标签名称</th>
            <th>描述</th>
            <th>头像</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="tag in filteredTags" :key="tag.id">
            <td>{{ tag.id }}</td>
            <td>
              <span class="tag-name">
                {{ tag.tagName }}
              </span>
            </td>
            <td>{{ tag.description || '暂无描述' }}</td>
            <td>
              <img v-if="tag.avatar" :src="tag.avatar" alt="标签头像" class="tag-avatar" />
              <span v-else class="no-avatar">无头像</span>
            </td>
            <td>{{ tag.remark || '无备注' }}</td>
            <td class="action-buttons">
              <button @click="viewTag(tag)" class="btn-view" title="查看详情">
                <i class="icon-view"></i>
                查看
              </button>
              <button @click="editTag(tag)" class="btn-edit" title="编辑">
                <i class="icon-edit"></i>
                编辑
              </button>
              <button @click="deleteTag(tag)" class="btn-delete" title="删除">
                <i class="icon-delete"></i>
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination">
      <button 
        @click="prevPage" 
        :disabled="currentPage === 1"
        class="btn-page"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页
      </span>
      <button 
        @click="nextPage" 
        :disabled="currentPage === totalPages"
        class="btn-page"
      >
        下一页
      </button>
    </div>

    <!-- 添加/编辑标签模态框 -->
    <div v-if="showAddTagModal || showEditTagModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h2>{{ showEditTagModal ? '编辑标签' : '添加标签' }}</h2>
          <button @click="closeModal" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveTag">
            <div class="form-group">
              <label for="name">标签名称</label>
              <input 
                type="text" 
                id="name" 
                v-model="tagForm.tagName" 
                required
              />
            </div>
            <div class="form-group">
              <label for="description">描述</label>
              <textarea 
                id="description" 
                v-model="tagForm.description" 
                rows="3"
              ></textarea>
            </div>
            <div class="form-group">
              <label for="avatar">头像URL</label>
              <input 
                type="text" 
                id="avatar" 
                v-model="tagForm.avatar"
                placeholder="请输入头像URL"
              />
            </div>
            <div class="form-group">
              <label for="remark">备注</label>
              <textarea 
                id="remark" 
                v-model="tagForm.remark" 
                rows="2"
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModal" class="btn-cancel">
                取消
              </button>
              <button type="submit" class="btn-primary">
                {{ showEditTagModal ? '保存' : '添加' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 标签详情模态框 -->
    <div v-if="showTagDetailModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h2>标签详情</h2>
          <button @click="showTagDetailModal = false" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <div class="tag-detail">
            <div class="detail-item">
              <span class="label">ID:</span>
              <span class="value">{{ selectedTag.id }}</span>
            </div>
            <div class="detail-item">
              <span class="label">标签名称:</span>
              <span class="tag-name">
                {{ selectedTag.tagName }}
              </span>
            </div>
            <div class="detail-item">
              <span class="label">描述:</span>
              <span class="value">{{ selectedTag.description || '暂无描述' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">头像:</span>
              <img v-if="selectedTag.avatar" :src="selectedTag.avatar" alt="标签头像" class="tag-avatar" />
              <span v-else class="no-avatar">无头像</span>
            </div>
            <div class="detail-item">
              <span class="label">备注:</span>
              <span class="value">{{ selectedTag.remark || '无备注' }}</span>
            </div>
          </div>
          <div class="modal-actions">
            <button @click="showTagDetailModal = false" class="btn-primary">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { tagApi } from '@/api/modules'

// 响应式数据
const tags = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalTags = ref(0)

// 模态框状态
const showAddTagModal = ref(false)
const showEditTagModal = ref(false)
const showTagDetailModal = ref(false)
const selectedTag = ref({})

// 标签表单
const tagForm = ref({
  id: null,
  tagName: '',
  description: '',
  avatar: '',
  remark: ''
})

// 计算属性
const filteredTags = computed(() => {
  let result = tags.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(tag => 
      tag.tagName.toLowerCase().includes(query) || 
      (tag.description && tag.description.toLowerCase().includes(query))
    )
  }

  return result
})

const totalPages = computed(() => {
  return Math.ceil(totalTags.value / pageSize.value)
})

// 生命周期钩子
onMounted(() => {
  fetchTags()
})

// 方法
const fetchTags = async () => {
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await tagApi.getTagPage(params)
    console.log('API返回数据:', response)
    
    // 处理API返回的数据结构
    if (response && response.code === 200 && response.data) {
      tags.value = response.data.list || []
      totalTags.value = response.data.total || 0
    } else {
      // 如果API返回的数据结构不符合预期，使用模拟数据
      console.warn('API返回数据结构不符合预期，使用模拟数据')
      tags.value = getMockTags()
      totalTags.value = tags.value.length
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    // 使用模拟数据作为后备
    tags.value = getMockTags()
    totalTags.value = tags.value.length
  }
}

const getMockTags = () => {
  return [
    {
      id: 1,
      tagName: '美女',
      avatar: '',
      description: '美女相关内容',
      remark: '热门标签'
    },
    {
      id: 2,
      tagName: '美食',
      avatar: 'https://example.com/food.jpg',
      description: '美食相关内容',
      remark: '美食分类'
    },
    {
      id: 3,
      tagName: '旅游',
      avatar: '',
      description: '旅游相关内容',
      remark: '旅游攻略'
    },
    {
      id: 4,
      tagName: '科技',
      avatar: 'https://example.com/tech.jpg',
      description: '科技相关内容',
      remark: '科技前沿'
    },
    {
      id: 5,
      tagName: '音乐',
      avatar: '',
      description: '音乐相关内容',
      remark: '音乐分享'
    }
  ]
}

const handleSearch = () => {
  currentPage.value = 1
  // 在实际应用中，这里应该调用API进行搜索
}



const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchTags()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchTags()
  }
}

const viewTag = (tag) => {
  selectedTag.value = { ...tag }
  showTagDetailModal.value = true
}

const editTag = (tag) => {
  tagForm.value = { ...tag }
  showEditTagModal.value = true
}

const saveTag = async () => {
  try {
    if (showEditTagModal.value) {
      // 编辑标签
      await tagApi.updateTag(tagForm.value.id, tagForm.value)
    } else {
      // 添加标签
      await tagApi.createTag(tagForm.value)
    }
    
    closeModal()
    fetchTags()
  } catch (error) {
    console.error('保存标签失败:', error)
  }
}

const enableTag = async (tag) => {
  try {
    await tagApi.enableTag(tag.id)
    fetchTags()
  } catch (error) {
    console.error('启用标签失败:', error)
  }
}

const disableTag = async (tag) => {
  if (confirm(`确定要禁用标签 ${tag.name} 吗？`)) {
    try {
      await tagApi.disableTag(tag.id)
      fetchTags()
    } catch (error) {
      console.error('禁用标签失败:', error)
    }
  }
}

const setHotTag = async (tag) => {
  try {
    await tagApi.updateTag(tag.id, { ...tag, isHot: true })
    fetchTags()
  } catch (error) {
    console.error('设置热门标签失败:', error)
  }
}

const unsetHotTag = async (tag) => {
  try {
    await tagApi.updateTag(tag.id, { ...tag, isHot: false })
    fetchTags()
  } catch (error) {
    console.error('取消热门标签失败:', error)
  }
}

const deleteTag = async (tag) => {
  if (confirm(`确定要删除标签 ${tag.tagName} 吗？此操作不可恢复！`)) {
    try {
      await tagApi.deleteTag(tag.id)
      fetchTags()
    } catch (error) {
      console.error('删除标签失败:', error)
    }
  }
}

const closeModal = () => {
  showAddTagModal.value = false
  showEditTagModal.value = false
  tagForm.value = {
    id: null,
    tagName: '',
    description: '',
    avatar: '',
    remark: ''
  }
}

const getStatusText = (status) => {
  const statusMap = {
    active: '启用',
    disabled: '禁用'
  }
  return statusMap[status] || status
}

const formatDate = (dateString) => {
  if (!dateString) return '从未'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped>
.tag-management {
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.btn-primary {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-primary:hover {
  background-color: #2563eb;
}

/* 搜索和筛选区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
  gap: 16px;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box input {
  width: 100%;
  padding: 10px 16px 10px 40px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
}

.search-box .icon-search {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.filter-options {
  display: flex;
  gap: 12px;
}

.filter-options select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
}

/* 表格样式 */
.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e2e8f0;
}

th {
  color: #475569;
  font-weight: 600;
  font-size: 14px;
  background-color: #f8fafc;
}

td {
  color: #334155;
  font-size: 14px;
}

tr:hover {
  background-color: #f8fafc;
}

/* 标签样式 */
.tag-name {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  color: #334155;
  font-weight: 500;
}

.color-preview {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}

/* 状态和热门标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background-color: #dcfce7;
  color: #166534;
}

.status-badge.disabled {
  background-color: #f1f5f9;
  color: #64748b;
}

.hot-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.hot-badge.hot {
  background-color: #fef3c7;
  color: #92400e;
}

.hot-badge.normal {
  background-color: #f1f5f9;
  color: #64748b;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons button {
  padding: 6px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.btn-view {
  background-color: #e0f2fe;
  color: #0369a1;
}

.btn-view:hover {
  background-color: #bae6fd;
}

.btn-edit {
  background-color: #dbeafe;
  color: #1e40af;
}

.btn-edit:hover {
  background-color: #bfdbfe;
}

.btn-enable {
  background-color: #dcfce7;
  color: #166534;
}

.btn-enable:hover {
  background-color: #bbf7d0;
}

.btn-disable {
  background-color: #f1f5f9;
  color: #475569;
}

.btn-disable:hover {
  background-color: #e2e8f0;
}

.btn-hot {
  background-color: #fef3c7;
  color: #92400e;
}

.btn-hot:hover {
  background-color: #fde68a;
}

.btn-unhot {
  background-color: #f1f5f9;
  color: #475569;
}

.btn-unhot:hover {
  background-color: #e2e8f0;
}

.btn-delete {
  background-color: #fee2e2;
  color: #b91c1c;
}

.btn-delete:hover {
  background-color: #fecaca;
}

/* 分页控件 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.btn-page {
  padding: 8px 16px;
  background-color: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-page:hover:not(:disabled) {
  background-color: #f8fafc;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #64748b;
  font-size: 14px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h2 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #64748b;
  cursor: pointer;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.color-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.color-picker {
  width: 50px;
  height: 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  cursor: pointer;
}

.color-text {
  flex: 1;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  width: auto;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.btn-cancel {
  padding: 8px 16px;
  background-color: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-cancel:hover {
  background-color: #f8fafc;
}

/* 标签详情样式 */
.tag-detail {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-item .label {
  min-width: 80px;
  color: #64748b;
  font-size: 14px;
}

.detail-item .value {
  color: #1e293b;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .modal {
    width: 95%;
  }
}
</style>